
package com.probiz.estoresa.system.web.action;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.common.model.system.Region;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.system.model.UserDefinedRegionFullyModel;
import com.probiz.estore.system.service.RegionItemManager;
import com.probiz.estore.system.service.RegionManager;
import com.probiz.estore.webapp.util.RequestUtil;

/**
 * 注意基类是Regiong而不是RegionItem
 *
 */
public class UserDefinedRegionController extends
		GenericStoreAdminController<Region> {
	private RegionItemManager	regionItemManager	= null;
	private RegionManager		regionManager		= null;

	public RegionItemManager getRegionItemManager() {
		return regionItemManager;
	}

	public void setRegionItemManager(RegionItemManager regionItemManager) {
		this.regionItemManager = regionItemManager;
	}

	public RegionManager getRegionManager() {
		return regionManager;
	}

	public void setRegionManager(RegionManager regionManager) {
		this.regionManager = regionManager;
	}

	@Override
	protected String getEntityName(Region entity) {
		return entity.getRegionName();
	}


	@Override
	protected void initController() throws Exception {
		mgr = regionManager;
		
	}

	@Override
	protected void preSave(HttpServletRequest request, Region entity,
			BindException errors) {
		
	}
	@Override
	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView(listView);
		mv.addObject("regionList", regionManager.getAllUserDefinedRegion());
		return mv;
	}
	
	
	@Override
	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model。因为要先保存其名称，否则可能会连I18N数据也已经删除了；另外可以用于出错的时候恢复显示Form页面
		Region entity = formBackingObject(request);
		
		// 删除并设置信息
		String entityId = request.getParameter(entityIdName);
		if (!StringUtils.isEmpty(entityId)) {
			// 先构造提示信息，否则信息对应的记录可能也会被删除。
			String entityName = getEntityName(entity);
			try {
				regionManager.deleteFullyForUserDefinedType(entity);
			} catch (DataIntegrityViolationException e) {
				e.printStackTrace();
				saveErrorMessage(request, this.getMessage("common.message.delete.constraintViolation"));
				
				// 为了出错的时候可以恢复表单显示，构造errors。无须作表单绑定和验证
				ServletRequestDataBinder binder = this.getDefaultBinder(request,entity);
				BindException errors = new BindException(binder.getBindingResult());
				
				return showForm(request, errors);
			}
			postDelete(request, entityName);
		} else {
			saveMessage(request, getMessage("errors.invalid.delete.id",	new Object[] { entityId }));
		}
		return getModelAndView(cancelFormView, null);
	}
	
	/**
	 * 批量删除记录。批量处理的模式：应该重用单个实体处理的方法，否则，就会出现处理不一致的情况。本模式能保证事务完整性。成功后重定向到列表页面，以消除重复提交问题。
	 * 
	 * @param request
	 * @param response
	 */
	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		// 取得要删除的记录的id的列表。注意：选择框的id要是"multiIds"。
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			try{
				for(String id:ids){
					Region region = regionManager.getById(Integer.valueOf(id));
					regionManager.deleteFullyForUserDefinedType(region);
				}
			}catch (DataIntegrityViolationException e) {
				//Hibernate底层仍会log此出错误信息
				this.saveErrorMessage(request, this.getMessage("common.message.delete.constraintViolation"));
				return this.returnToSearch(request, response);
			}
			String message = getMessage("common.deleted.multi", new Object[] {
					getEntityTypeMessage(), ids.length });
			saveMessage(request, message);
		}
		return getModelAndView(cancelFormView, null);
	}
	
	
	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		Region entity = formBackingObject(request);

		BindException errors = null;
		try {
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				
				regionManager.saveFullyForUserDefinedType(getUserDefinedRegionFullyModel(request,entity));
				postSave(request, entity);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		ModelAndView mav;
		if (errors.hasErrors()) {
			mav = showForm(request, errors);
		} else {
			mav = getRedirectToActionView("edit", ((BaseObject) entity).getId()
					.toString());
		}
		return mav;
	}
	

    // 构造自定义地区模型，方便保存
	private UserDefinedRegionFullyModel getUserDefinedRegionFullyModel(HttpServletRequest request,
			Region region) {
		UserDefinedRegionFullyModel model = new UserDefinedRegionFullyModel();
        model.setRegion(region);

        // ---------- start:绑定值--------------
		String[] regionItemIds = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "regionItemIds"));
		String[] regionItemItemIds = RequestUtil.getParameterValuesNullSafe(request,
				"itemIds");
        model.setRegionItemIds(regionItemIds);
		model.setRegionItemItemIds(regionItemItemIds);
		// --------- end:绑定值----------------
        return model;
    }
	

}
